package com.qk.management.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtils;
import com.qk.domian.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * @Author:Shuna
 * @Date: 2025/10/07 18:15
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    private static final String DEFAULT_PASSWORD_SUFFIX = "123";
    private static final Integer USER_STATUS_NORMAL = 1;
    private static final Integer USER_STATUS_DISABLE = 0;

    @Override
    public PageResult<UserDO> list(UserDTO userDTO) {
        PageHelper.startPage(userDTO.getPage(), userDTO.getPageSize());
        List<UserDO> result = userMapper.selectByPage(userDTO);
        for (UserDO userDO : result) {
            userDO.setPhone(DesensitizedUtil.mobilePhone(userDO.getPhone()));
        }
        Page<UserDO> page = (Page<UserDO>) result;
        return PageResult.<UserDO>builder().total(Long.valueOf(page.getTotal()).intValue()).rows(page.getResult()).build();
    }

    @Override
    public void add(User user) {

        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        String rawPassword = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFFIX).toString();
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);
        userMapper.insert(user);

    }

    @Override
    public void update(User user) {
        boolean hasNull = BeanUtil.hasNullField(user, "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public List<User> getByRoleLabel(String roleLabel) {
        return userMapper.selectByRoleLabel(roleLabel);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        boolean isNotEmpty = CollectionUtil.isNotEmpty(ids);
        if (!isNotEmpty) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        userMapper.deleteBatch(ids);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {

        boolean hasNullField = BeanUtil.hasNullField(dto);
        if (hasNullField) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        User dbuser = userMapper.selectByUsername(dto.getUsername());
        if (Objects.isNull(dbuser)) {
            CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
        }

        if (ObjectUtil.equals(dbuser.getStatus(), USER_STATUS_DISABLE)){
            CommonException.throwCommonException(ParamEnum.LOGIN_STATUS_ERROR);
        }

        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        String encodedPassword = dbuser.getPassword();
        boolean isChecked = ObjectUtil.equals(userPassword, encodedPassword);
        if (!isChecked) {
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }

        Role role = roleMapper.selectById(dbuser.getRoleId());

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", dbuser.getId());
        claims.put("username", dbuser.getUsername());
        String jwt = JwtUtils.generateToken(claims);

        return UserLoginVO.builder()
                .id(dbuser.getId())
                .username(dbuser.getUsername())
                .name(dbuser.getName())
                .image(dbuser.getImage())
                .roleLabel(role.getLabel())
                .token(jwt)
                .build();
    }


}
